package com.jd.fruit.controller.mobile;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jd.fruit.exception.CartException;
import com.jd.fruit.model.admin.order.Address;
import com.jd.fruit.model.admin.order.Order;
import com.jd.fruit.model.admin.order.OrderItem;
import com.jd.fruit.model.admin.order.ShoppingCart;
import com.jd.fruit.model.admin.shop.Goods;
import com.jd.fruit.model.admin.shop.GoodsSku;
import com.jfinal.kit.StrKit;

/**
 * 
 * 购物车
 * 
 * 
 */
public class CartEntity {

	private static final String CART_COOKIE_KEY = "jogo_cart_cookie_key_id";

	private List<ShoppingCart> items = new ArrayList<ShoppingCart>();
	private String userId = null;
	

	/**
	 * 增加
	 * 
	 * @param goodsId
	 * @param goodsNumber
	 */
	public void addItem(String goodsId, int goodsNumber,HttpServletRequest req,HttpServletResponse res) {
		if(isLogin(req)){
			ShoppingCart.dao.addCartItem(goodsId, goodsNumber, userId);
		}else{
			this.initByCookie(req);
			ShoppingCart item = new ShoppingCart(goodsId, goodsNumber,this.userId);
			int index = -1;
			if ((index = items.indexOf(item)) != -1) {
				ShoppingCart old = items.get(index);
				int oldnum = old.getInt("goods_number");
				old.set("goods_number", oldnum + goodsNumber);
			} else {
				items.add(item);
			}
			this.persistByCookie(res);
		}
	}

	/**
	 * 减少购物车中商品数量
	 * 
	 * @param goodsId
	 * @param goodsNumber
	 */
	public void updateNum(String goodsId, int goodsNumber,HttpServletRequest req,HttpServletResponse res) {
		if(isLogin(req)){
			ShoppingCart.dao.updateCartItem(goodsId, goodsNumber, userId);
		}else{
			this.initByCookie(req);
			ShoppingCart item = new ShoppingCart(goodsId, goodsNumber,this.userId);
			int index = -1;
			if ((index = items.indexOf(item)) != -1) {
				ShoppingCart old = items.get(index);
				old.set("goods_number", goodsNumber);
				// 当数量小于1时，则表示产品要在购物车中删除
				if (old.getInt("goods_number") <= 0) {
					items.remove(index);
				}
			}
		}
	}

	/**
	 * 直接删除产品
	 * 
	 * @param id
	 */
	public void removeItem(String id,String cartId,HttpServletRequest req,HttpServletResponse res) {
		if(isLogin(req)){
			ShoppingCart.dao.removeCartItem(cartId);
		}else{
			ShoppingCart item = new ShoppingCart(id, 0,this.userId);
			items.remove(item);
		}
	}

	/**
	 * 获得被选中的元素列表
	 * 
	 * @return
	 */
	public List<ShoppingCart> getItems() {
		return items;
	}

	/**
	 * 获得被选中的元素列表
	 * 
	 * @return
	 */
	public List<ShoppingCart> getCheckedItems(boolean moreInfo) {
		List<ShoppingCart> result = new ArrayList<ShoppingCart>();
		for (ShoppingCart item : items) {
			if (item.getInt("is_checked")==1) {
				if (moreInfo) {
					/**
					 * 获得标题，价格及其他信息
					 */
					// 获得标题，价格及其他信息
					GoodsSku sku = GoodsSku.dao.findById(item.getStr("goods_sku_id"));
					String goodsId = sku.getStr("goods_id");
					Goods goods = Goods.dao.findById(goodsId);
					item.put("name", goods.getStr("goods_name"));
					item.put("shopname", "JOGO SHOP");
					item.put("price", sku.getDouble("price"));
					item.put("goods_image", sku.getStr("goods_image"));
					item.put("desc", sku.getStr("attr_value"));
					
				}
				result.add(item);
			}
		}
		return result;
	}

	/**
	 * 
	 * @param json
	 */
	public void setJsonAsItems(String json) {
		items.clear();
		JSONArray array = JSONArray.parseArray(json);
		for (Object object : array) {
			JSONObject goodsJson = (JSONObject) object;
			if (goodsJson != null && !goodsJson.isEmpty()) {
				String id = goodsJson.getString("id");
				int num = goodsJson.getInteger("num");
				ShoppingCart item = new ShoppingCart(id, num,this.userId);
				try {
					String checked = goodsJson.getString("checked");
					if ("1".equals(checked)) {
//						item.setChecked(true);
						item.set("is_checked", 1);
					}
				} catch (Exception e) {
				}
				items.add(item);
			}
		}
	}
	
	

	/**
	 * 
	 * @return
	 */
	public JSONArray getItemsAsJson(boolean moreInfo) {
		JSONArray result = new JSONArray();
		for (ShoppingCart item : items) {
			JSONObject obj = new JSONObject();
			obj.put("id", item.getStr("id"));
			obj.put("goods_sku_id", item.getStr("goods_sku_id"));
			obj.put("goods_number", item.getInt("goods_number"));
			obj.put("is_checked", item.getInt("is_checked"));
			if (moreInfo) {
				// 获得标题，价格及其他信息
				GoodsSku sku = GoodsSku.dao.findById(item.getStr("goods_sku_id"));
				String goodsId = sku.getStr("goods_id");
				Goods goods = Goods.dao.findById(goodsId);
				obj.put("name", goods.getStr("goods_name"));
				obj.put("shopname", "JOGO SHOP");
				obj.put("price", sku.getDouble("price"));
				obj.put("goods_image", sku.getStr("goods_image"));
				obj.put("desc", sku.getStr("attr_value"));
			}
			result.add(obj);
		}
		return result;
	}

	/**
	 * 
	 * @return
	 */
	public JSONArray getItemsAsJson() {
		return getItemsAsJson(true);
	}

	
	
	/**
	 * 更新选中状态，只有参数中id对应的item，状态置为checked
	 * 
	 * @param checkedIds
	 */
	public void updateChecked(Collection<String> checkedIds) {
		for (ShoppingCart item : items) {
//			item.setChecked(false);
			item.set("is_checked", 0);
			if (checkedIds.contains(item.getStr("goods_sku_id"))) {
				item.set("is_checked", 1);
			}
		}
	}
	
	public void updateItemChecked(String cartId,int is_checked){
		ShoppingCart cart = new ShoppingCart();
		cart.set("id", cartId);
		cart.set("is_checked", is_checked);
		cart.update();
	}

	/**
	 * 获得数量统计
	 * 
	 * @return
	 */
	public int getItemCount() {
		int count = 0;
		for (ShoppingCart item : items) {
			count = item.getInt("goods_number") + count;
		}
		return count;
	}

	/**
	 * 只统计被选中的元素数量
	 * 
	 * @return
	 */
	public int getCheckedItemCount() {
		int count = 0;
		for (ShoppingCart item : items) {
			if (item.getInt("is_checked")==1) {
				count = item.getInt("goods_number") + count;
			}
		}
		return count;
	}

	/**
	 * 获得已选择产品总价
	 * 
	 * @return
	 */
	public double getCheckedItemSum() {
		return sum(true);
	}

	/**
	 * 获得所有产品总价
	 * 
	 * @return
	 */
	public double getItemSum() {
		return sum(false);
	}

	private double sum(boolean onlySumChecked) {
		Double sum = Double.valueOf(0);
		for (ShoppingCart item : items) {
			if (onlySumChecked && item.getInt("is_checked")==0) {
				continue;
			}
			String skuId = item.getStr("goods_sku_id");
			GoodsSku goodsSku = GoodsSku.dao.findById(skuId);
			Double price = goodsSku.getDouble("price");
			if (price == null) {
				continue;
			}
			sum = item.getInt("goods_number") * price;
		}
		return sum.doubleValue();
	}

	/**
	 * 将cookie中购物车状态恢复
	 * 
	 * @param req
	 */
	void initByCookie(HttpServletRequest req) {
		// 是否已经登录
		if(isLogin(req)){
			ShoppingCart cart = new ShoppingCart();
			cart.set("user_id", this.getUserId());
			items = ShoppingCart.dao.list();
		}else{
			Cookie[] cookies = req.getCookies();
			for (int i = 0; cookies != null && i < cookies.length; i++) {
				Cookie cookie = cookies[i];
				if (cookie.getName().equals(CART_COOKIE_KEY)) {
					setJsonAsItems(cookie.getValue());
					break;
				}
			}
		}
	}
	
	boolean isLogin(HttpServletRequest req){
		this.setUserId("1");
		return true;
	}
	
	void persist(HttpServletResponse res) {
		if(StrKit.notBlank(this.userId)){
			persistByDatabase(this.userId,res);
		}else{
			persistByCookie(res);
		}
	}

	/**
	 * 将购物车内容持久化入cookie中
	 * 
	 * @param res
	 */
	void persistByCookie(HttpServletResponse res) {
		Cookie cookie = new Cookie(CART_COOKIE_KEY, getItemsAsJson(false)
				.toString());
		cookie.setMaxAge(Integer.MAX_VALUE);
		// cookie.setHttpOnly(true);
		res.addCookie(cookie);
	}
	
	/**
	 * 将购物车内容持久化入DataBase中
	 * 
	 * @param res
	 */
	void persistByDatabase(String userId,HttpServletResponse res) {
		ShoppingCart.dao.persistCartEntity(this, userId);
		this.items.clear();
		persistByCookie(res);
	}
	
	void cartPay(HttpServletRequest req,String addressId) throws CartException{
		if(isLogin(req)){
			this.initByCookie(req);
			List<ShoppingCart> carts = this.getCheckedItems(false);
			Order order = new Order();
			int orderGoodsNumber = 0;
			double orderPriceSum = 0;
			List<OrderItem> itemList = new ArrayList<OrderItem>();
			for(ShoppingCart cart :carts){
				String goodsSkuId = cart.get("goods_sku_id");
				int goodsNumber = cart.getInt("goods_number");
				GoodsSku sku = GoodsSku.dao.findById(goodsSkuId);
				Goods goods = Goods.dao.findById(sku.getStr("goods_id"));
				int skuGoodsNumber = sku.getInt("stocks");
				if( skuGoodsNumber >= goodsNumber ){
					OrderItem item = new OrderItem();
					item.set("goods_sku_id", goodsSkuId);
					item.set("goods_number", goodsNumber);
					double price = sku.getDouble("price");
					item.set("goods_price", price);
					String goodsName = goods.getStr("goods_name");
					item.set("goods_name", goodsName);
					item.set("goods_sku_desc", sku.getStr("attr_value"));
					itemList.add(item);
					orderGoodsNumber = orderGoodsNumber + goodsNumber;
					orderPriceSum =  price + orderPriceSum; 
				} else {
					throw new  CartException("001","库存不足!");
				}
			}
			String order_note = "";
			Address address = Address.dao.findById(addressId);
			
			order.set("order_count_money", orderPriceSum);
			order.set("order_goods_number", orderGoodsNumber);
			order.set("user_id", this.userId);
			order.set("postage", 0);
			order.set("order_note", order_note);
			order.set("order_status", 1);
			order.set("consignee", address.getStr("consignee"));
			order.set("consignee_tel", address.getStr("tel"));
			order.set("consignee_address", address.getStr("detail_address"));
			
//			order.set("shop_user_id", shop_user_id);
//			order.set("shop_id", shop_id);
			Order.dao.save(order);
			for(OrderItem item : itemList){
				item.set("order_id", order.getStr("id"));
				item.save();
			}
			
		}else{
			throw new  CartException("000","没有登录!");
		}
		
	}
	
	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}


	
}
